﻿using Aker.DevTeam;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Aker
{
    public partial class Orders : XForm
    {
        public Orders()
        {
            InitializeComponent();
        }


        private void Orders_Load(object sender, EventArgs e)
        {
            if (Data.IsLookupInitialized)
                Bind();
            else
                Data.LookupInitialized += Bind;

        }

        private void Bind()
        {
            //DataTable dtFairs = Data.DM.ExecuteDataTableByQuery("select distinct isnull(Fair,'') Fair from [Order] where IsOnline = 0");

            //cmbFairs.Items.Add("Showroom Orders");
            //foreach (DataRow dr in dtFairs.Rows)
            //{
            //    string fair = dr["Fair"].ToString();
            //    cmbFairs.Items.Add(fair);
            //}

            Data.TAM.OrderTableAdapter.Fill(Data.DB.Order);
            Data.TAM.OrderLinesTableAdapter.Fill(Data.DB.OrderLines);

            FillProductDetail();

            Data.DB.Order.AcceptChanges();
            Data.DB.OrderLines.AcceptChanges();


            BarcodeRead += Orders_BarcodeRead;

            this.Text = Language.Fair.Orders;
            gvOrder.ViewCaption = Language.Fair.Orders;
            gvOrderLines.ViewCaption = Language.Fair.OrderDetail;




            gvOrder.Init(Data.bsOrder);
            gvOrderLines.Init(Data.bsOrderLines);






            gvOrder.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvOrderLines.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

            RepositoryItemMemoExEdit ri = new RepositoryItemMemoExEdit();
            ri.ShowIcon = false;
            gvOrder.Columns["Address"].ColumnEdit = ri;
            gvOrder.Columns["PrivateNotes"].ColumnEdit = ri;

            gvOrder.Columns["Notes"].ColumnEdit = ri;
            gvOrderLines.Columns["Notes"].ColumnEdit = ri;

            gvOrder.AddSummary();
            gvOrder.MakeColumnsReadOnly("OrderId", "SyncDate", "EditDate", "eMailDate");

            gvOrderLines.MakeColumnInvisible("OrderId", "OrderLinesId");
            if (AppSession.IsOnline)
            {
                gvOrder.MakeColumnInvisible("SyncDate", "IsOnline");
            }



            gvOrderLines.MakeColumnsReadOnly("ProductId");
            gvOrderLines.FormatAsNumber("PriceEuro", "PriceDollar", "Price2Euro", "Price2Dollar", "Price3Euro", "Price3Dollar");
            gvOrderLines.MakeColumnsReadOnly("PriceEuro", "PriceDollar", "Price2Euro", "Price2Dollar", "Price3Euro", "Price3Dollar");
            gvOrderLines.AddSummary();


            int visibleIndex = gvOrderLines.Columns["ProductId"].VisibleIndex + 1;

            gvOrderLines.CustomUnboundColumnData += gvOrderLines_CustomUnboundColumnData;

            foreach (string col in Data.ProductDetails)
            {
                GridColumn gcTemp = gvOrderLines.Columns[col];
                gcTemp.OptionsColumn.AllowEdit = false;
                gcTemp.VisibleIndex = visibleIndex++;
                gcTemp.FilterMode = ColumnFilterMode.DisplayText;
            }

            GridManager gmOrder = GridManager.GetManager(gvOrder);
            GridManager gmOrderLines = GridManager.GetManager(gvOrderLines);

            gvOrder.FocusedRowChanged += gvOrder_FocusedRowChanged;
            gvOrder.CustomColumnDisplayText += gvOrder_CustomColumnDisplayText;
            gvOrder.MoveLast();



            gmOrder.GridMenu.AddMenu(Language.Fair.AddProduct, AddProductManual_Click);
            gmOrder.GridMenu.AddMenu(Language.Fair.PrintOrders, PrintOrder_Click, true);
            gmOrder.GridMenu.AddMenu(Language.Fair.PrintOrderArticle, PrintOrderArticles_Click);
            gmOrder.GridMenu.AddMenu(Language.Fair.EditBusinessCard, EditOrder, true);

            if (!AppSession.IsOnline)
                gmOrder.GridMenu.AddMenu(Language.Fair.SyncRows, Sync_Click, true);

            gmOrder.GridMenu.AddMenu(Language.Fair.SendMails, SendMail_Click);
            gmOrder.GridMenu.AddMenu(Language.Fair.MarkAsSend, MarkAsSent_Click, true);
            gmOrder.GridMenu.AddMenu(Language.Fair.DeleteSelected, DeleteOrder_Click, true);

            GridColumn gc = new GridColumn();
            gc.Name = "Remove";
            gc.Caption = "Remove";
            gc.FieldName = "Remove";
            gc.VisibleIndex = 900;
            gvOrderLines.Columns.Add(gc);

            gc = new GridColumn();
            gc.Name = "Thumb";
            gc.Caption = "Thumb";
            gc.FieldName = "Thumb";
            gc.VisibleIndex = 0;
            gvOrderLines.Columns.Add(gc);
            gvOrderLines.MakeColumnsReadOnly("Thumb");

            if (AppSession.Language == "TR")
            {
                gvOrder.SetCaptions("OrderId:SipNo", "SyncOrderId:SenkSipNo", "Brand:Marka", "Contact:İlgili", "Email:e-posta", "Address:Adres", "Phone:Telefon", "Fair:Fuar", "Season:Sezon", "PrivateNotes:Özel Notlar",
                    "WebSite:Web Sitesi", "Country:Ülke", "BusinessCardId:Kart Vizit", "Notes:Notlar", "Cancelled:İptal", "IncludePhoto:Resimler Dahil", "eMailDate:eposta Tarihi", "EditDate:Düzeneleme Tarihi",
                    "InsertDate:Eklenme Tarihi", "CarrierCustomerInfo:Kargo Müşteri Bilgisi", "CarrierTrackNumber:Kargo Takip No", "Currency:Parabirimi"
                    );

                gvOrderLines.SetCaptions("ProductId:Artikel Id", "Thumb:Resim", "Article:Artikel", "Design:Desen", "Composition:Karışm", "Width:En", "Weight:Ağırlık", "Meter:Metre", "Notes:Notlar",
                    "PriceEuro:FiyatEuro", "Price2Euro:Fiyat2Euro", "Price3Euro:Fiyat3Euro",
                    "PriceDollar:FiyatDollar", "Price2Dollar:Fiyat2Dollar", "Price3Dollar:Fiyat3Dollar"
                    , "SpecialPrice:Özel Fiyat", "Cancelled:İptal", "Remove:Sil"
                    );
            }


            gvOrder.BestFitColumns();



            gvOrder.RowStyle += gvOrder_RowStyle;
            gvOrder.RowCellStyle += gvOrder_RowCellStyle;
            gvOrder.RowCellClick += gvOrder_RowCellClick;
            gvOrder.ValidateRow += gvOrder_ValidateRow;
            gvOrder.InvalidRowException += gvOrder_InvalidRowException;
            gvOrderLines.RowCellClick += gvOrderLines_RowCellClick;
            gvOrderLines.CustomDrawCell += gvOrderLines_CustomDrawCell;


            gvOrderLines.CustomColumnDisplayText += gvOrderLines_CustomColumnDisplayText;


            gvOrderLines.RowCellStyle += gvOrderLines_RowCellStyle;
            gvOrderLines.ValidateRow += gvOrderLines_ValidateRow;
            gvOrderLines.InvalidRowException += gvOrderLines_InvalidRowException;

            gvOrder.RowHeight = 15;
            gvOrder.OptionsView.RowAutoHeight = false;



            gvOrderLines.BestFitColumns();


            //gvOrderLines.RowHeight = 50;
            gvOrderLines.CalcRowHeight += gvOrderLines_CalcRowHeight;

            gvOrderLines.Columns["Remove"].Width = 28;

            if (AppSession.UserInfo.YetkiId == 1)
            {
                gvOrder.MakeReadOnly();
                gvOrder.RowCellClick -= gvOrder_RowCellClick;

                gmOrder.GridMenu.RemoveMenu(Language.Fair.AddProduct);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.SyncRows);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.SendMails);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.MarkAsSend);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.DeleteSelected);

                gvOrderLines.MakeReadOnly();
                gvOrderLines.RowCellClick -= gvOrderLines_RowCellClick;
                gvOrderLines.MakeColumnInvisible("Remove");
            }
            else if (AppSession.UserInfo.YetkiId == 3)
            {
                gvOrder.MakeReadOnly();
                gvOrder.RowCellClick -= gvOrder_RowCellClick;

                gmOrder.GridMenu.RemoveMenu(Language.Fair.AddProduct);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.SendMails);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.MarkAsSend);
                gmOrder.GridMenu.RemoveMenu(Language.Fair.DeleteSelected);

                gvOrderLines.MakeReadOnly("SpecialPrice");
                gvOrderLines.RowCellClick -= gvOrderLines_RowCellClick;
                gvOrderLines.MakeColumnInvisible("Remove");
            }

            gvOrder.MakeColumnInvisible("UserId", "PriceType", "BusinessCard", "IrsaliyeAciklama");
        }

        void gvOrder_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "BusinessCardId")
            {
                if (e.Value.ToIntNN() > -1)
                    e.DisplayText = "*";
                else
                    e.DisplayText = "";
            }
        }

        //string prevCurrency = "";
        void gvOrder_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            string currency = gvOrder.GetFocusedRowCellValue("Currency").ToStringNN();
            int priceType = gvOrder.GetFocusedRowCellValue("PriceType").ToIntNN();
            if (priceType == -1)
                priceType = UserSettings.PriceType;

            if (currency == "")
                currency = Settings.Currency;

            //if (currency != prevCurrency)
            {
                SetCurrencyColumns(currency, priceType);
                //prevCurrency = currency;
            }
        }

        private void SetCurrencyColumns(string currency, int priceType)
        {
            //foreach (GridColumn gc in gvOrderLines.Columns)
            //{
            //    if (gc.FieldName.ToLower().StartsWith("price"))
            //        gc.Visible = true;
            //}

            int columnIndex = gvOrderLines.VisibleColumns.Count - 4;

            if (currency == "$")
            {
                if (priceType == 0)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["PriceDollar"].VisibleIndex = columnIndex;
                }
                else if (priceType == 1)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["Price2Dollar"].VisibleIndex = columnIndex;
                }
                else if (priceType == 2)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");

                    gvOrderLines.Columns["Price3Dollar"].VisibleIndex = columnIndex;
                }
                else if (priceType == 3)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["FiyatExtra"].VisibleIndex = columnIndex;
                    //gvOrderLines.Columns["PriceExtra"].VisibleIndex = columnIndex;
                }
            }
            else
            {
                if (priceType == 0)
                {
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["PriceEuro"].VisibleIndex = columnIndex;
                }
                else if (priceType == 1)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["Price2Euro"].VisibleIndex = columnIndex;
                }
                else if (priceType == 2)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["Price3Euro"].VisibleIndex = columnIndex;
                }
                else if (priceType == 3)
                {
                    gvOrderLines.MakeColumnInvisible("PriceEuro");
                    gvOrderLines.MakeColumnInvisible("Price2Euro");
                    gvOrderLines.MakeColumnInvisible("Price3Euro");
                    gvOrderLines.MakeColumnInvisible("PriceDollar");
                    gvOrderLines.MakeColumnInvisible("Price2Dollar");
                    gvOrderLines.MakeColumnInvisible("Price3Dollar");

                    gvOrderLines.Columns["FiyatExtra"].VisibleIndex = columnIndex;
                    //gvOrderLines.Columns["PriceExtra"].VisibleIndex = columnIndex;
                }
            }
        }

        private void EditOrder(object sender, EventArgs e)
        {
            int orderId = gvOrder.GetFocusedRowCellValue("OrderId").ToIntNN();
            if (orderId > 0)
            {
                using (NewOrder no = new NewOrder(orderId))
                {
                    no.ShowDialog();
                }
            }
            else
            {
                XtraMessageBox.Show(Language.Fair.FirstSelect, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        void gvOrderLines_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            if (Data.ProductDetails.Contains(e.Column.FieldName))
            {

                GridView view = sender as GridView;
                int ProductId = view.GetListSourceRowCellValue(e.ListSourceRowIndex, "ProductId").ToIntNN();

                if (ProductId > -1)
                {
                    DataRow pr = Data.DB.Product.Select("ProductId = " + ProductId)[0];

                    if (pr != null)
                        e.Value = pr[e.Column.FieldName].ToString();
                }
            }
        }

        private void FillProductDetail()
        {
            foreach (DataRow dr in Data.DB.OrderLines.Select("isnull(Article,'') = ''"))
            {
                int productId = dr["ProductId"].ToIntNN();


                if (productId > -1)
                {
                    DataRow pr = Data.DB.Product.FindByProductId(productId);

                    if (pr != null)
                        foreach (string col in Data.ProductDetails)
                            dr[col] = pr[col];
                }
            }
        }

        void gvOrderLines_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (!gvOrderLines.IsFilterRow(e.RowHandle))
                e.RowHeight = 50;
        }

        private void AddProductManual_Click(object sender, EventArgs e)
        {
            AddProduct adder = new AddProduct();
            adder.ProductSelected += adder_ProductSelected;
            adder.ShowDialog();
        }

        void adder_ProductSelected(int productId, string artikel)
        {
            Orders_BarcodeRead(productId);
        }

        private void Orders_BarcodeRead(int ProductId)
        {
            AkerDB.ProductRow product = Data.DB.Product.FindByProductId(ProductId);
            if (product != null)
            {
                int OrderId = (int)gvOrder.GetFocusedRowCellValue("OrderId");

                if (Data.DB.OrderLines.Select(string.Format("OrderId={0} and ProductId={1}", OrderId, ProductId)).Length > 0)
                    Console.Beep();
                else
                {
                    //foreach (AkerDB.OrderLinesRow dr in Data.DB.OrderLines.Select("OrderId=" + OrderId.ToString()))
                    //    Data.DB.OrderLines.RemoveOrderLinesRow(dr);

                    AkerDB.OrderLinesRow ol = Data.DB.OrderLines.NewOrderLinesRow();
                    ol.ProductId = ProductId;

                    if (!product.IsPriceDollarNull())
                        ol.PriceDollar = product.PriceDollar;

                    if (!product.IsPriceEuroNull())
                        ol.PriceEuro = product.PriceEuro;

                    if (!product.IsPrice2DollarNull())
                        ol.Price2Dollar = product.Price2Dollar;

                    if (!product.IsPrice2EuroNull())
                        ol.Price2Euro = product.Price2Euro;

                    if (!product.IsPrice3DollarNull())
                        ol.Price3Dollar = product.Price3Dollar;

                    if (!product.IsPrice3EuroNull())
                        ol.Price3Euro = product.Price3Euro;

                    ol.OrderId = OrderId;
                    ol.Cancelled = false;
                    Data.DB.OrderLines.AddOrderLinesRow(ol);
                    Data.SaveOrderLines();

                    gvOrderLines.BestFitColumns();
                    int rowHandle = gvOrderLines.LocateByValue("ProductId", ProductId);
                    gvOrderLines.MakeRowVisible(rowHandle);
                    gvOrderLines.FocusedRowHandle = rowHandle;

                    FillProductDetail();
                }
            }
        }

        private void SendMail_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            List<DataRow> drs = new List<DataRow>();
            foreach (int rowHandle in gvOrder.GetSelectedRows())
                drs.Add(gvOrder.GetDataRow(rowHandle));

            AppSession.MainForm.Info = Data.SendEmail(drs.ToArray());

            this.Cursor = Cursors.Default;
        }

        private void Sync_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            List<DataRow> drs = new List<DataRow>();
            foreach (int rowHandle in gvOrder.GetSelectedRows())
                drs.Add(gvOrder.GetDataRow(rowHandle));

            AppSession.MainForm.Info = Data.Sync(drs.ToArray());

            this.Cursor = Cursors.Default;
        }

        private void MarkAsSent_Click(object sender, EventArgs e)
        {
            foreach (int rowHandle in gvOrder.GetSelectedRows())
            {
                DataRow dr = gvOrder.GetDataRow(rowHandle);
                if (dr["eMailDate"] == DBNull.Value)
                    dr["eMailDate"] = DateTime.Now;
            }
            Data.SaveOrder();
        }

        private void DeleteOrder_Click(object sender, EventArgs e)
        {
            List<int> orderIds = new List<int>();
            foreach (int rowHandle in gvOrder.GetSelectedRows())
            {
                int orderId = (int)gvOrder.GetRowCellValue(rowHandle, "OrderId");
                orderIds.Add(orderId);
            }

            if (orderIds.Count < 1)
            {
                XtraMessageBox.Show(Language.Fair.FirstSelect, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (AppSession.IsOnline)
            {
                if (XtraMessageBox.Show(Language.Fair.DeleteConfirmation + "(" + orderIds.Count + Language.Data.Items + ")", Language.Uyari, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    foreach (int orderId in orderIds)
                    {
                        foreach (DataRow dr in Data.DB.OrderLines.Select("OrderId=" + orderId))
                            dr.Delete();

                        Data.DB.Order.FindByOrderId(orderId).Delete();
                    }

                    Data.SaveOrderOrderLines();
                }
            }
            else
            {
                if (XtraMessageBox.Show(Language.Fair.OfflineDeleteConfirmation + "(" + orderIds.Count + Language.Data.Items + ")", Language.Uyari, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    foreach (int orderId in orderIds)
                    {
                        foreach (DataRow dr in Data.DB.OrderLines.Select("OrderId=" + orderId))
                            dr.Delete();

                        Data.DB.Order.FindByOrderId(orderId).Delete();
                    }
                    Data.SaveOrderOrderLines();
                }
            }

        }

        private void PrintOrderArticles_Click(object sender, EventArgs e)
        {
            if (gvOrderLines.DataRowCount < 1)
                return;

            string list = string.Empty;

            for (int i = 0; i < gvOrderLines.DataRowCount; i++)
                list += gvOrderLines.GetDataRow(i)["ProductId"] + ",";

            list = list.Substring(0, list.Length - 1);

            AppSession.MainForm.ShowMdiChildForm(typeof(Products), list);
            return;

            //DataSet dsReport = Data.DM.ExecuteDataSet("GetProductReport", list);

            //ProductReportSettings el = new ProductReportSettings();
            //el.DisableManualOrdering();
            //el.ShowDialog();

            //int counter = Convert.ToInt32(el.emptyCount.Value);
            //int copyCount = Convert.ToInt32(el.copyCount.Value);

            //ProductReport pr = new ProductReport(dsReport, counter, copyCount);

            //pr.ShowPreview();
        }

        private void splitter_SizeChanged(object sender, EventArgs e)
        {
            splitter.SplitterPosition = (splitter.Horizontal ? splitter.Width : splitter.Height) / 2 + 40;

        }

        private void PrintOrder_Click(object sender, EventArgs e)
        {
            int[] selectedRows = gvOrder.GetSelectedRows();

            if (selectedRows.Length == 0)
                return;


            AkerDB.OrderRow oRow = (AkerDB.OrderRow)gvOrder.GetDataRow(selectedRows[0]);
            int orderId = oRow.OrderId;
            bool eng = oRow.Country != "Turkey";
            bool includePhoto = oRow.IncludePhoto;

            //includePhoto = true;
            includePhoto = false;

            DataSet dsReport = Data.DM.ExecuteDataSet("GetOrderReport", orderId, Settings.TerminalNo, Settings.FairNo);

            OrderReport r1 = new OrderReport(dsReport.Copy(), false, eng, includePhoto);
            r1.CreateDocument();

            OrderReport r2 = new OrderReport(dsReport.Copy(), true, eng, includePhoto);
            r2.CreateDocument();
            r1.Pages.AddRange(r2.Pages);

            for (int i = 1; i < selectedRows.Length; i++)
            {
                oRow = (AkerDB.OrderRow)gvOrder.GetDataRow(selectedRows[i]);
                int tempOrderId = oRow.OrderId;
                eng = oRow.Country != "Turkey";

                DataSet dsTemp = Data.DM.ExecuteDataSet("GetOrderReport", tempOrderId, Settings.TerminalNo, Settings.FairNo);

                r2 = new OrderReport(dsTemp.Copy(), false, eng, includePhoto);
                r2.CreateDocument();
                r1.Pages.AddRange(r2.Pages);

                r2 = new OrderReport(dsTemp.Copy(), true, eng, includePhoto);
                r2.CreateDocument();
                r1.Pages.AddRange(r2.Pages);
            }

            r1.PrintingSystem.ContinuousPageNumbering = false;

            ReportPrintTool printTool = new ReportPrintTool(r1);
            printTool.ShowPreviewDialog();
        }

        private void gvOrderLines_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            try
            {
                if (e.Column.Name == "Remove" && e.RowHandle > -1)
                {
                    int iconYIndent = (e.Bounds.Height - 16) / 2;
                    e.Graphics.DrawImage(Aker.Properties.Resources.DeleteMenuItem, e.Bounds.X + 1, e.Bounds.Y + iconYIndent);

                    //  e.DisplayText = "X";
                    //e.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
                    //e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Underline);
                    e.Handled = true;
                }
                else if (e.Column.FieldName == "Thumb" && e.RowHandle > -1)
                {
                    int productId = -1;
                    int.TryParse(gvOrderLines.GetRowCellValue(e.RowHandle, "ProductId").ToStringNN(), out productId);
                    if (productId > -1)
                    {
                        AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(productId);

                        if (!pr.IsThumbnailNull())
                        {
                            MemoryStream ms = new MemoryStream(pr.Thumbnail);
                            e.Graphics.DrawImage(Image.FromStream(ms), e.Bounds.X, e.Bounds.Y);
                            e.Handled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrder_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Cancelled")
            {
                object currentVal = e.CellValue;
                if (currentVal == null || currentVal == DBNull.Value || (bool)currentVal == true)
                    gvOrder.SetRowCellValue(e.RowHandle, "Cancelled", false);
                else
                    gvOrder.SetRowCellValue(e.RowHandle, "Cancelled", true);

                Data.SaveOrder();
            }
            else if (e.Column.FieldName == "BusinessCardId")
            {
                int bcId = e.CellValue.ToIntNN();
                if (bcId > -1)
                {
                    DataRow dr = Data.DM.ExecuteDataTableByQuery("select BusinessCard from BusinessCard where BusinessCardId =" + bcId.ToString()).Rows[0];
                    ImageViewer iv = new ImageViewer();
                    iv.picture.EditValue = dr["BusinessCard"];
                    iv.ShowDialog();
                }
            }
        }

        private void gvOrder_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            try
            {
                string fieldName = e.Column.FieldName;
                if (fieldName == "SyncDate" && e.RowHandle > -1)
                {
                    if (e.CellValue != null && e.CellValue != DBNull.Value)
                        e.Appearance.BackColor = Color.Gold;
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrder_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle > -1)
                {
                    if ((bool)gvOrder.GetRowCellValue(e.RowHandle, "Cancelled"))
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                    }
                    else if (gvOrder.GetRowCellValue(e.RowHandle, "CarrierTrackNumber").ToStringNN() != "")
                    {
                        e.Appearance.BackColor = Color.Aqua;
                    }
                    else
                    {
                        if (e.RowHandle == gvOrder.FocusedRowHandle)
                            e.Appearance.BackColor = e.Appearance.BackColor = Color.YellowGreen;
                        else
                            e.Appearance.Combine((e.RowHandle & 1) != 0 ? gvOrder.Appearance.EvenRow : gvOrder.Appearance.OddRow);
                    }
                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrderLines_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            try
            {
                string fieldName = e.Column.FieldName;
                if ("Meter Notes".Contains(fieldName))
                    e.Appearance.BackColor = Color.LemonChiffon;
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        private void gvOrderLines_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "Remove")
            {
                if (XtraMessageBox.Show("Are you sure to remove the product?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    //int OrderId = (int)gvOrder.GetFocusedRowCellValue("OrderId");
                    //int ProductId = (int)gvOrderLines.GetRowCellValue(e.RowHandle, "ProductId");

                    //foreach (DataRow dr in Data.DB.OrderLines.Select("OrderId=" + OrderId.ToString()))
                    //  Data.DB.OrderLines.Rows.Remove(gvOrderLines.GetDataRow(e.RowHandle));

                    //Data.DB.OrderLines.Rows[0].dele

                    gvOrderLines.GetDataRow(e.RowHandle).Delete();



                    Data.SaveOrderLines();

                    //DataSet dsData = Data.DM.ExecuteDataSet("DelOrderLines", OrderId, ProductId);
                    //dsData.Tables[0].TableName = "OrderLines";
                    //Data.DB.Merge(dsData);
                    //gvOrderLines.BestFitColumns();
                }
            }
            else if (e.Column.FieldName == "Cancelled")
            {
                object currentVal = e.CellValue;
                if (currentVal == null || currentVal == DBNull.Value || (bool)currentVal == true)
                    gvOrderLines.SetRowCellValue(e.RowHandle, "Cancelled", false);
                else
                    gvOrderLines.SetRowCellValue(e.RowHandle, "Cancelled", true);

                Data.SaveOrderLines();
            }
            else if (e.Column.FieldName == "Thumb")
            {
                int productId = (int)gvOrderLines.GetFocusedRowCellValue("ProductId");

                AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(productId);

                if (!pr.IsThumbnailNull())
                {
                    ImageViewer iv = new ImageViewer(productId);
                    iv.ShowDialog();
                }
            }
        }



        private void gvOrderLines_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
        }

        private void gvOrder_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
        }

        private void gvOrder_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            DialogResult result = XtraMessageBox.Show(Language.Fair.Submit, Language.Uyari, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                e.Valid = true;

                int cellOrderId = (int)gvOrder.GetRowCellValue(e.RowHandle, "OrderId");
                Data.DB.Order.Select("OrderId=" + cellOrderId)[0]["EditDate"] = DateTime.Now;

                gvOrder.EndEditing();

                DataRowView dv = e.Row as DataRowView;
                Data.SaveOrder(dv.Row);
            }
            else
            {
                e.Valid = false;
            }
        }

        private void gvOrderLines_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
        }

        private void gvOrderLines_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            DialogResult result = XtraMessageBox.Show(Language.Fair.Submit, Language.Uyari, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                int cellOrderId = (int)gvOrderLines.GetRowCellValue(e.RowHandle, "OrderId");
                Data.DB.Order.Select("OrderId=" + cellOrderId)[0]["EditDate"] = DateTime.Now;

                gvOrderLines.EndEditing();

                Data.SaveOrderOrderLines();
            }
            else
            {
                e.Valid = false;
            }
        }

        public void AddNewOrder()
        {
            using (NewOrder newOrder = new NewOrder())
            {
                DialogResult dr = newOrder.ShowDialog();

                if (dr == DialogResult.OK)
                {

                    gvOrder.MoveLastVisible();
                    gvOrder.MakeRowVisible(gvOrder.FocusedRowHandle);
                }

                this.Cursor = Cursors.Default;
            }
        }

        private void btnBind_Click(object sender, EventArgs e)
        {

        }
    }
}